import uploader from 'kuan-utils/lib/uploader'
import axios from 'axios'
import { aliToken } from '@/api/uploadToken'

export default async () => {
  const { file, md5 } = await uploader.getFile()
  const suffix = file.name.substring(
    file.name.lastIndexOf('.') || 0,
    file.name.length
  )
  const name = md5 + suffix
  const tokenData = await aliToken()
  const { accessid, callback, dir, host, policy, signature } = tokenData

  const formData = {
    'x:module': ''
  }
  formData['key'] = `${dir}${name}`
  formData['OSSAccessKeyId'] = accessid
  formData['policy'] = policy
  formData['Signature'] = signature
  formData['callback'] = callback

  const fd = new FormData()

  Object.entries(formData).forEach(([key, value]) => {
    fd.append(key, value)
  })

  fd.append('file', file)

  const { data, status } = await axios({
    url: host,
    method: 'post',
    data: fd
  })

  if (status === 200) {
    return data
  }
  return Promise.reject(data)
}
